import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { useUserStore } from "../store/user";
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("../views/main.vue"),
    redirect: "/home",
    children: [
      {
        path: "/home",
        component: () => import("../views/home.vue"),
      },
      {
        path: "/cart",
        component: () => import("../views/cart.vue"),
      },
      {
        path: "/mine",
        component: () => import("../views/mine.vue"),
      },
    ],
  },
  {
    path: "/detail",
    component: () => import("../views/detail.vue"),
  },
  {
    path: "/reg",
    component: () => import("../views/reg.vue"),
  },
  {
    path: "/login",
    component: () => import("../views/login.vue"),
  },
  {
    path: "/order",
    component: () => import("../views/order.vue"),
  },
  {
    path: "/address",
    component: () => import("../views/address/index.vue"),
  },
  {
    path: "/test",
    component: () => import("../test/index.vue"),
  },
  {
    path: "/pinia",
    component: () => import("../views/pinia/index.vue"),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
const blackList = ["/cart", "/mine"];
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  console.log(userStore.userInfo);
  if (to.path.indexOf("login") == -1) {
    if (blackList.includes(to.path)) {
      if (userStore.userInfo) {
        next();
      } else {
        next({
          path: "/login",
          query: {
            target: to.path,
          },
        });
      }
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
